package club.banyuan;

import club.banyuan.util.HrmSession;
import club.banyuan.util.SessionUtil;

import java.io.BufferedReader;
import java.io.IOException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;

public class Request {
    private String url;
    private int contentLength;
    private String data;
    private String host;
    private HrmSession session;
    private Map<String,String > cookie=new HashMap<>();
    private int total;
    private int code;
    private int page;
    private int rows;
    private int id;
    private String message = "";

    //Getter and Setter


    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getTotal() {
        return total;
    }

    public void setTotal(int total) {
        this.total = total;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public int getPage() {
        return page;
    }

    public void setPage(int page) {
        this.page = page;
    }

    public int getRows() {
        return rows;
    }

    public void setRows(int rows) {
        this.rows = rows;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public HrmSession getSession() {
        return session;
    }

    public void setSession(HrmSession session) {
        this.session = session;
    }

    public Map<String, String> getCookie() {
        return cookie;
    }

    public void setCookie(Map<String, String> cookie) {
        this.cookie = cookie;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public int getContentLength() {
        return contentLength;
    }

    public void setContentLength(int contentLength) {
        this.contentLength = contentLength;
    }

    public String getData() {
        return data;
    }

    public void setData(String data) {
        this.data = data;
    }

    private void addData(String data){this.data+=("&"+data);}

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    //根据form格式解析数据
    //key=value&key1=value1
    public Map<String, String> getFormData() {
        Map<String, String> rlt = new HashMap<>();
        String[] pairs = data.split("&");
        // 为了处理 key=&key1= 空值的情况
        for (String pair : pairs) {
            String[] entry = pair.split("=");
            if (entry.length > 1) {
                rlt.put(entry[0], entry[1]);
            } else if (entry.length == 1) {
                rlt.put(entry[0], "");
            }
        }
        return rlt;
    }

    public static Request parse(BufferedReader reader) throws IOException {
        Request request = new Request();
        //读取第一行,获取请求路径
        // GET /server/user/list HTTP/1.1
        // GET 表示浏览器发送的HTTP请求方式
        String url = reader.readLine();
        if (url != null && url.length() > 0) {
            StringTokenizer tokenizer = new StringTokenizer(url);
            //浏览器发送HTTP请求的方式
            tokenizer.nextToken();
            //获取url
            url = tokenizer.nextToken();
            System.out.println("=========");
            System.out.println("请求的路径是: " + url);
        } else {
            System.out.println("资源路径不合法");
            return null;
        }
        request.setUrl(url);
        //读取头部信息
        String line = reader.readLine();
        int contentLength = 0;
        while (line != null && line.length() != 0) {
            System.out.println(line);
            //Content-Length: 0
            if (line.startsWith("Content-Length: ")) {
                contentLength = Integer.parseInt(line.replaceAll("Content-Length: ", ""));
            }
            //Host: 127.0.0.1:5000
            else if (line.startsWith("Host: ")) {
                String host = line.replaceAll("Host: ", "");
                request.setHost(host);
            }else if (line.startsWith("Cookie: ")){
                processSession(request,line);
            }
            line = reader.readLine();
        }
        if (request.getSession()==null){
            HrmSession session=new HrmSession();
            request.setSession(session);
            SessionUtil.setSession(session);
        }
        request.setContentLength(contentLength);
        System.out.println("读取头部信息结束");

        //读取数据
        //url尾部有数据
        if(url.contains("?")){
            String[] splits=url.split("\\?");
            request.setUrl(splits[0]);
            request.setData(splits[1]);
        }
        //contentLength!=0时的FormData
        if (contentLength > 0) {
            char[] buf=new char[contentLength];
            int count=reader.read(buf);
            if (count!=contentLength){
                throw new RuntimeException("读取数据失败,长度不匹配, "+count+": "+contentLength);
            }
            String reqData=new String(buf);
            //打印请求数据
            reqData= URLDecoder.decode(reqData, StandardCharsets.UTF_8);
            System.out.println("请求发送的数据:\n"+reqData);

            request.addData(reqData);
        }
        return request;
    }

    private static void processSession(Request request, String line) {
        String[] split = line.replaceAll("Cookie: ", "").split(";");
        for (String s : split) {
            String[] keyValue=s.trim().split("=");
            request.getCookie().put(keyValue[0],keyValue[1]);
        }
        if (request.getCookie().containsKey("SESSIONID")){
            String sessionId=request.getCookie().get("SESSIONID");
            HrmSession session=SessionUtil.getSession(sessionId);
            request.setSession(session);
        }
    }
}